//
//  AttributeValueFormatter.m
//  Task Views
//
//  Created by Chris Karr on 2/18/09.
//  Copyright 2009 Chris J. Karr. All rights reserved.
//

#import <AddressBook/AddressBook.h>
#import "AttributeValueFormatter.h"

@implementation AttributeValueFormatter

- (NSString *) stringForObjectValue:(id)anObject
{
	if ([anObject isKindOfClass:[NSString class]])
		return [anObject description];
	else if ([anObject isKindOfClass:[NSNumber class]])
		return [anObject description];
	else if ([anObject isKindOfClass:[NSDate class]])
	{
		[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
		
		NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
		[formatter setDateStyle:NSDateFormatterShortStyle];
		[formatter setTimeStyle:NSDateFormatterNoStyle];
		
		NSString * formattedString = [formatter stringForObjectValue:anObject];
		
		[formatter release];
		
		return formattedString;
	}
	else if ([anObject isKindOfClass:[NSArray class]])
	{
		if ([anObject count] > 0)
		{
			NSString * lastDesc = [[anObject lastObject] description];
		
			ABAddressBook * ab = [ABAddressBook sharedAddressBook];
			
			if ([lastDesc hasSuffix:@":ABPerson"])
			{
				NSMutableArray * peopleNames = [NSMutableArray array];
				
				NSEnumerator * iter = [anObject objectEnumerator];
				NSString * uniqueId = nil;
				while (uniqueId = [iter nextObject])
				{
					ABRecord * record = [ab recordForUniqueId:uniqueId];
					
					NSString * name = nil;
					
					if ([record isKindOfClass:[ABGroup class]])
						name = [record valueForProperty:kABGroupNameProperty];
					else
						name = [NSString stringWithFormat:@"%@ %@", [record valueForProperty:kABFirstNameProperty],
								[record valueForProperty:kABLastNameProperty]];
					
					if (name != nil)
						[peopleNames addObject:name];
				}

				return [peopleNames componentsJoinedByString:@"; "];
			}
			else
				return [anObject componentsJoinedByString:@"; "];
		}
		else
			return @"";
	}
	else
		return [anObject description];
}

- (BOOL)getObjectValue:(id *)anObject forString:(NSString *)string errorDescription:(NSString **)error
{
	*anObject = string;
	
	return YES;
}

@end
